package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Dict;
import com.bwie.mapper.DictMapper;
import com.bwie.service.DictService;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: 鑫仔
 * @Date: 2025/7/22 11:26
 * @Description:
 **/
@Transactional
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private DictMapper dictMapper;




    @Override
    public R getDictByType(Integer dictType) {
        String key = "dict-" + dictType;
        Boolean b = redisTemplate.hasKey(key);
        log.info("从redis获取");
        if (b) {
            List<Object> objects = redisTemplate.opsForHash().values(key);
            ArrayList<Object> list = new ArrayList<>();
            for (Object object : objects) {
                Dict dict = JSON.parseObject(object.toString(), Dict.class);
                list.add(dict);
            }
        }
        log.info("从数据库获取");
        List<Dict> dicts = dictMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getDictType, dictType));
        for (Dict dict : dicts) {
            String key1 = "dict-" + dict.getDictType();
            String key2 = "" + dict.getDictId();
            redisTemplate.opsForHash().put(key1, key2, JSON.toJSONString(dict));
        }
        return R.OK(dicts);
    }
}
